<?php
/**
 * Created by PhpStorm.
 * User: win
 * Date: 2018/8/13
 * Time: 14:14
 */

namespace AppBundle\Controller;

use AppBundle\Entity\Invoice;
use AppBundle\Entity\Pay\Order;
use AppBundle\Entity\Pay\OrderItem;
use AppBundle\Entity\Pay\OrderShip;
use AppBundle\Entity\Pay\HarvesterReceiveAddress;
use AppBundle\Entity\Pay\ReportReceiveAddress;
use AppBundle\Entity\Pay\WaxBlockReceiveAddress;
use AppBundle\Entity\Pay\ShopCart;
use AppBundle\Exception\AbstractException;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Controller\Tool\UnionPayController;
use AppBundle\Controller\Tool\WxPayController;
use AppBundle\Controller\Tool\InvoiceController;

//use AppBundle\Controller\Tool\UnionPayController;
class BankPayController extends CommonController
{
    const PAYMENT_STATUS_WAIT = 1;//待付款
    const PAYMENT_STATUS_SUCCESS = 2;//已付款
    const PAYMENT_STATUS_HARVESTER_SEND = 3;//采集器寄送中
    const PAYMENT_STATUS_SAMPLE_SEND = 4;//样本回寄中
    const PAYMENT_STATUS_RECEIVED = 5;//样本已接收，实验中
    const PAYMENT_STATUS_REFUND_APPLY = 6;//申请退款
    const PAYMENT_STATUS_REFUND_REFUND = 7;//拒绝退款
    const PAYMENT_STATUS_REFUND_WAIT = 8;//待退款
    const PAYMENT_STATUS_REFUNDED = 9;//退款完成
    const PAYMENT_STATUS_COMPLETE = 10;//交易完成
    const PAYMENT_STATUS_CLOSED = 11;//交易关闭
    const PAYMENT_STATUS_ALL = 100;//全部订单
    private $url = "https://api.cmburl.cn:8065/polypay/v1.0/mchorders/qrcodeapply";
    private $appId = "8ab74856-8772-45c9-96db-54cb30ab9f74";
    private $appSecret = "5b96f20a-011f-4254-8be8-9a5ceb2f317f";
    //    private static final String appId = "8ab74856-8772-45c9-96db-54cb30ab9f74";
//    private static final String appSecret = "5b96f20a-011f-4254-8be8-9a5ceb2f317f";
    private $notifyUrl = "http://app.repugene.com:3131/bank/pay/order/notify";
    // 表单提交字符集编码
    public $postCharset = "UTF-8";
    private $fileCharset = "UTF-8";

    /**
     *
     * 样本生成pdf
     * @Route("/bank/pay/qrcode/apply",name="bank_pay_qrcode_apply")
     * @Method("POST)
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function qrcodeapply()
    {
        $txnAmt=$this->request('txnAmt');
        $user_id = $request->get('user_id');
        if(!$txnAmt||!$user_id){
            Throw new AbstractException('参数错误！');
        }
        $orderid = $this->payOrderNumCreate();
        //生成订单插入到系统里
        $params = array(
            'body' => '聚合支付测试',
            'currencyCode' => '156',
            'merId' => '30899910742007M',
            'notifyUrl' => 'http://app.repugene.com:3131/bank/pay/order/notify',
            'orderId' => '' . $orderid,
            'payValidTime' => 1200,
            'termId' => '00774411',
            'txnAmt' => '1',
            'userId' => 'N003280919',
            'tradeScene' => 'OFFLINE',
        );
        $params = json_encode($params);
        $curl = curl_init();
        $sinaddHead=array(
            "Content-Type: application/json",
            "Postman-Token: d15e7b3f-705d-4376-b44c-5f849d019fdf",
            "cache-control: no-cache"
        );
        $sinAddUrl='http://10.1.8.89:8888/api/v1/sign/add';
        // $addUrl='http://10.1.8.89:8888/api/v1/sign/add';
        $sinAddparams= $params
        $signResult=$this->postCurl($sinAddUrl,  $sinAddparams, $headers = array(), $second = 30)
        // cCURLOPT_ENCODING => "",
        //         //     CUurl_setopt_array($curl, array(
        //     CURLOPT_PORT => "8888",
        //     CURLOPT_URL => "http://10.1.8.89:8888/api/v1/sign/add",
        //     CURLOPT_RETURNTRANSFER => true,
        //     RLOPT_MAXREDIRS => 10,
        //     CURLOPT_TIMEOUT => 30,
        //     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        //     CURLOPT_CUSTOMREQUEST => "POST",
        //     CURLOPT_POSTFIELDS => $params,
        //     CURLOPT_HTTPHEADER => array(
        //         "Content-Type: application/json",
        //         "Postman-Token: d15e7b3f-705d-4376-b44c-5f849d019fdf",
        //         "cache-control: no-cache"
        //     ),
        // ));
        // $signResult = curl_exec($curl);
        // $err = curl_error($curl);
        // curl_close($curl);
        $signResultMap = json_decode($signResult, true);
        try {
            $signResult = $signResult;
            $sysParams['appid'] = $this->appId;
            $sysParams['secret'] = $this->appSecret;
            $signResult = $signResultMap['signResult'];
            $timestamps = $signResultMap['timestamp'];
            $sysParams['timestamps'] = $timestamps;
            $sysParams['sign'] = $signResult['sign'];
            $apiSignString = $signResultMap['apiSign'];
            $signResult = json_encode($signResult);
//            var_dump('signresult是：' . $signResult);
//            echo "</br>";
//            var_dump('timestamp是：' . $timestamps);
//            echo "</br>";
//            var_dump('apisign是：' . $apiSignString);

//            echo "</br>";
            $qrcodeApplyUrl="https://api.cmburl.cn:8065/polypay/v1.0/mchorders/qrcodeapply";
            $qrcodeApplyParms=$signResult;
            $qrcodeApplyHeades=array(
                "Content-Type: application/json",
                "Postman-Token: 2ce01a59-2f46-4666-b599-a9a8b812fc74",
                "appid: 8ab74856-8772-45c9-96db-54cb30ab9f74",
                "timestamp: $timestamps",
                "apisign:   $apiSignString",
                "cache-control: no-cache"
            ;
            $response =$this->postCurl($qrcodeApplyUrl,  $qrcodeApplyParms, $qrcodeApplyHeades = array(), $second = 30)

            // $curl = curl_init();
            // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            // curl_setopt_array($curl, array(
            //     CURLOPT_PORT => "8065",
            //     CURLOPT_URL => "https://api.cmburl.cn:8065/polypay/v1.0/mchorders/qrcodeapply",
            //     CURLOPT_RETURNTRANSFER => true,
            //     CURLOPT_ENCODING => "",
            //     CURLOPT_MAXREDIRS => 10,
            //     CURLOPT_TIMEOUT => 30,
            //     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            //     CURLOPT_CUSTOMREQUEST => "POST",
            //     CURLOPT_POSTFIELDS => $signResult,
            //     CURLOPT_HTTPHEADER => array(
            //         "Content-Type: application/json",
            //         "Postman-Token: 2ce01a59-2f46-4666-b599-a9a8b812fc74",
            //         "appid: 8ab74856-8772-45c9-96db-54cb30ab9f74",
            //         "timestamp: $timestamps",
            //         "apisign:   $apiSignString",
            //         "cache-control: no-cache"
            //     ),
            // ));
            // $response = curl_exec($curl);
            // curl_close($curl);
            // if ($err) {
            //     echo "cURL Error #:" . $err;
            // } else {
            //     //echo $response;
            // }

            $sinCheckUrl="http://10.1.8.89:8888/api/v1/sign/check";
            $sinCheckParms=$response;
            $sinCheckHeades=array(
                "Content-Type: application/json",
                "Postman-Token: c4e004e5-1812-4928-bad5-1cb765a80092",
                "cache-control: no-cache"
            );
            $checkResult1 =$this->postCurl($sinCheckUrl,  $sinCheckParms, $sinCheckHeades = array(), $second = 30);
            if(!$checkResult1){
                return $this->suc('错误！', ['response' => $response]);
            }else{
                return $this->suc('订单生成成功！', ['response' => $response]);
            }
//             $curl = curl_init();
//             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//             curl_setopt_array($curl, array(
//                 CURLOPT_PORT => "8888",
//                 CURLOPT_URL => "http://10.1.8.89:8888/api/v1/sign/check",
//                 CURLOPT_RETURNTRANSFER => true,
//                 CURLOPT_ENCODING => "",
//                 CURLOPT_MAXREDIRS => 10,
//                 CURLOPT_TIMEOUT => 30,
//                 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//                 CURLOPT_CUSTOMREQUEST => "POST",
//                 CURLOPT_POSTFIELDS => $response,
//                 CURLOPT_HTTPHEADER => array(
//                     "Content-Type: application/json",
//                     "Postman-Token: c4e004e5-1812-4928-bad5-1cb765a80092",
//                     "cache-control: no-cache"
//                 ),
//             ));
//             $checkResult1 = curl_exec($curl);
//             $err = curl_error($curl);
//             curl_close($curl);
//             if ($err) {
//                 echo "cURL Error #:" . $err;
//             } else {
//                // echo $response;
//             }
//             if (!$checkResult1) {
//                 return;
//             }
// //
//         } catch (Exception $e) {
//        //     print($e->getTraceAsString());
//             return false;
//         }

    }




    /**
     * 以post方式发起http调用
     *
     * @param string $url url
     * @param array $params post参数
     * @param int $second url执行超时时间，默认30s
     * @throws NnuoException
     */
    private static function postCurl($url, $params, $headers = array(), $second = 30)
    {
        $ch = curl_init();
        $curlVersion = curl_version();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_error($ch);
            curl_close($ch);
            throw newAbstractException("curl出错:$error");
        }
    }
    /**
     * 订单提交页面数据
     * @Route("bank/pay/order/page",name="bank_order_page_show")
     */
    public function payOrderDataShow(Request $request)
    {
        $user_id = $request->get('user_id');
        $test_code_info = $request->get('test_code',null);
        if(!$test_code_info) Throw new AbstractException('参数错误！');
        $test_code_info = json_decode($test_code_info,true);
        $test_code_arr = array_column($test_code_info,'test_code');//提取test_code
        $num = array_column($test_code_info,'num')[0];//立即购买数量
        $res = $this->getTestCodeRe()->getOrderDataShow($test_code_arr, $user_id, $shop_cart)->getResult();
        if(!$res) Throw new AbstractException('无数据！');
        $total = 0;
        foreach($res as $item => $value) {
            $unit_price = $value['unit_price'];
            foreach($test_code_info as $k => $v) {
                if($value['test_code'] == $v['test_code']) {
                    if($v['promotion_code']) {
                        $promotion_entity = $this->getRepository('AppBundle:PromotionCode')->findOneBy(['promotion_code'=>$v['promotion_code'],'test_code'=>$value['test_code']]);
                        if($promotion_entity) {
                            $promotion_amount = $promotion_entity->getPromotionAmount();
                            $unit_price = $value['unit_price'] - $promotion_amount;
                            if($unit_price < 0)
                                Throw new AbstractException('优惠码金额错误，请联系相关人员！');
                        }
                    }
                }
            }
            if(!isset($res[$item]['num'])) {
                $res[$item]['num'] = $num;
            }
            $subtotal = $unit_price * $res[$item]['num'];
            $res[$item]['subtotal'] = $subtotal;
            $total += $subtotal;
        }
        return $this->suc('ok',['info'=>$res,'totalAmount'=>$total]);
    }

    /**
     * 创建订单号
     */
    public function payOrderNumCreate()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderNum = $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) .
            date('d') . substr(time(), -5) . substr(microtime(), 2, 5) .
            sprintf('%02d', rand(0, 99));
        return $orderNum;
    }

    /**
     * 生成订单，包括order表，order_item表，以及order_ship
     * @Route("bank/pay/order/create",name="bank_order_create")
     * @Method("POST")
     */
    public function payOrderCreate(Request $request)
    {
        $user_id = $request->get('user_id');//用户编号
        $total_amount = $request->get('total_amount', null);//订单总金额
        $product_detail = $request->get('product_detail');//产品详情
        if (!$user_id || !$product_detail || !$total_amount)
            Throw new AbstractException('参数错误！');
        $user = $this->UsersRepository()->find($user_id);
        if (!$user) Throw new AbstractException('非法用户，请重新登录！');
        //检测订单编号是否重复
        $temp = 0;
        $order_num = '';
        while ($temp < 1) {
            $order_num = $this->payOrderNumCreate();//订单编号生成
            $order_entity = $this->getOrderRe()->findBy(['order_num' => $order_num]);
            if (!$order_entity)
                $temp = 1;
        }
        $order = new Order();
        $order->setOrderNum($order_num);
        $order->setUserId($user_id);
        $order->setStatus(self::PAYMENT_STATUS_WAIT);
        $order->setCreateTime(date('Y-m-d H:i:s', time()));
        $order->setUpdateTime(date('Y-m-d H:i:s', time()));
        $this->em()->persist($order);
        $total_num = 0;//订单总数量
        $total_price = 0;//订单总金额
        $product_detail = json_decode($product_detail, true);
        #循环遍历插入订单详情
        foreach ($product_detail as $k => $v) {
            if (!$v['test_code'] || !$v['num'])
                Throw new AbstractException('订单参数异常！');
            $test_code_entity = $this->getTestCodeRe()->findOneBy(['test_code' => $v['test_code'], 'app_show' => [1, 2]]);
            if (!$test_code_entity) Throw new AbstractException('检测内容不存在！');
            //查找sample_price价格表
            $sample_price_entity = $this->getSamplePriceRe()->findOneBy(['test_code' => $v['test_code'], 'price_desc' => '价格A', 'if_msi' => null, 'if_pdl1' => null]);
            if (!$sample_price_entity)
                Throw new AbstractException('该检测项目无价格！');
            if (!is_numeric($v['num']) || strpos($v['num'], ".") || $v['num'] < 0)
                Throw new AbstractException('数量参数异常！');
            $promotion_amount = 0;
            if (isset($v['promotion_code']) && !empty($v['promotion_code'])) {
                $promotionEntity = $this->getRepository('AppBundle:PromotionCode')->findOneBy(['test_code' => $v['test_code'], 'promotion_code' => $v['promotion_code']]);
                if ($promotionEntity)
                    $promotion_amount = $promotionEntity->getPromotionAmount();
                else
                    Throw new AbstractException('优惠码填写错误！请检查！');


            $price = $sample_price_entity->getUnitPrice() - $promotion_amount;//减去优惠价后的单价
            $total_fee = $v['num'] * $price;//小计
            if ($total_fee != $v['subtotal'])
                Throw new AbstractException('小计结果计算错误！请联系相关人员！');
            $orderItem = new OrderItem();
            $total_fee = $v['num'] * $price;
            $orderItem->setTestCode($v['test_code']);
            $orderItem->setOrderNum($order_num);
            $orderItem->setNum($v['num']);
            $orderItem->setTitle($test_code_entity->getTestName());
            $orderItem->setPrice($price);
            $orderItem->setTotalFee($total_fee);
            $orderItem->setPicPath($test_code_entity->getIntroducePic());
            $orderItem->setCreateTime(date('Y-m-d H:i:s'));
            $orderItem->setStatus(self::PAYMENT_STATUS_WAIT);;
            $total_num += $v['num'];
            $total_price += $total_fee;
            $this->em()->persist($orderItem);
            if (isset($v['cid']) && $v['cid']) {
                $shopCartEntity = $this->getShopCartRe()->find($v['cid']);
                if (!$shopCartEntity)
                    throw new AbstractException('购物车商品失效！');
                $this->remove($shopCartEntity);
            }
        }
        if ($total_amount != $total_price)
            Throw new AbstractException('总计结果计算错误！请联系相关人员！');
        $order->setTotalPrice($total_price);
        $order->setTotalNum($total_num);
        #插入订单收货地址
        $this->em()->persist($orderShip);
        $this->em()->getConnection()->beginTransaction();
        try {
            $this->flush();
            $this->em()->getConnection()->commit();

            return $this->suc('订单生成成功！', ['order_num' => $order_num, 'total_price' => $total_price]);
        } catch (\Exception $exception) {
            $this->em()->getConnection()->rollBack();
            echo $exception->getMessage();
            return $this->err('订单生成失败！');
        }
    }

    /**
     * 订单列表
     * @Route("bank/pay/order/list",name="bank_order_list")
     * @Method("GET")
     */
    public function payOrderList(Request $request)
    {
        $user_id = $request->get('user_id');
        $pageparam = $this->pageQuery($request);
        $status = explode(',', $request->get('status', 100));
        $user_entity = $this->getRepository('AppBundle:User\Users')->find($user_id);
        if (!$user_entity) Throw new AbstractException('用户ID异常！');
        if ($status[0] == self::PAYMENT_STATUS_ALL) //全部订单
        {
            $orderInfo = $this->getOrderRe()->getOrderInfoAll($user_id, $pageparam)->getArrayResult();
        } else {
            $orderInfo = $this->getOrderRe()->getOrderInfo($user_id, $pageparam, $status)->getArrayResult();
        }
        foreach ($orderInfo as $key => $value) {
            $order_num = $value['order_num'];
            $orderItems = $this->getOrderItemRe()->createQueryBuilder('p')
                ->select('p.order_num', 'p.test_code', 'p.num', 'p.price', 'p.title', 'p.total_fee', 'p.pic_path')
                ->where('p.order_num = :order_num')->setParameter('order_num', $order_num)
                ->getQuery()->getArrayResult();
            $orderInfo[$key]['product_detail'] = $orderItems;
        }
        return $this->suc('ok', $orderInfo);
    }

    /**
     * 订单详情接口
     * @Route("bank/pay/order/show",name="bank_order_show")
     * @Method("GET")
     */
    public function payOrderShow(Request $request)
    {
        $user_id = $request->get('user_id');
        $order_num = $request->get('order_num');//订单编号
        if (!$order_num) throw new AbstractException('订单编号不存在');
        //$order_entity = $this->getOrderRe()->findBy(['order_num'=>$order_num,'user_id'=>$user_id]);
        //if(!$order_entity) throw new AbstractException('订单编号非本人所属！');
        try {
            $data = $this->getOrderRe()->getOrderInfoDetail($order_num)->getSingleResult();
        } catch (NoResultException $e) {
            Throw new AbstractException('未找到对应订单！');
        } catch (NonUniqueResultException $e) {
            Throw new AbstractException('订单编号不唯一！');
        }
        $order_item_entities = $this->getOrderItemRe()->createQueryBuilder('p')
            ->select('p.order_num', 'p.test_code', 'p.num', 'p.title', 'p.price', 'p.total_fee', 'p.pic_path'
                , 'p.create_time', 'p.sample_code', 'p.status', 'p.refund_fee', 'p.refund_reason', 'p.refund_time', 'tc.test_name')
            ->leftJoin('AppBundle:Lab\TestCode', 'tc', 'WITH', 'p.test_code = tc.test_code')
            ->where('p.order_num = :order_num')
            ->setParameter('order_num', $order_num)->getQuery()->getArrayResult();
        $data['product_detail'] = $order_item_entities;
        return $this->suc('ok', $data);
    }
    /**
     * 支付加签接口，支付接口
     * @Route("bank/pay/order/payment",name="bank_order_payment")
     * @Method("POST")
     */
    public function payOrderPayment(Request $request)
    {
        $order_num = $request->get('order_num');//订单编号
        $pay_type = $request->get('pay_type');//支付类型
        $user_id = $request->get('user_id');//支付类型
        if (!$order_num || !$pay_type || !$user_id)
            Throw new AbstractException('参数异常！');
        $user_entity = $this->getRepository('AppBundle:User\Users')->find($user_id);
        if (!$user_entity) Throw new AbstractException('用户ID异常！');
        $order_entity = $this->getOrderRe()->findOneBy(['order_num' => $order_num, 'user_id' => $user_id, 'status' => self::PAYMENT_STATUS_WAIT]);
        if (!$order_entity) Throw new AbstractException('用户订单不存在！');
        $total_price = $order_entity->getTotalPrice();
        if (!is_numeric($total_price) || $total_price < 0) Throw new AbstractException('订单总金额异常！');
        $subject = '瑞普基因检测';
        $body = '精准健康医疗';
        $expire = '60';
        $str = '';
        if ($pay_type = 'unionpay') {
            $aliPay = new UnionPayController();
            $str = $aliPay->aliTradeAppPay($order_num, $subject, $body, $total_price, $expire);
        }
        return $this->suc('ok', ['payStr' => $str, 'totalPrice' => $total_price]);
    }

    /**
     * 支付交易查询接口
     * @Route("bank/pay/order/query",name="bank_order_query")
     * @Method("GET")
     * @param Request $request
     */
    public function payOrderQuery(Request $request)
    {
        $order_num = $request->get('order_num');//订单编号
        $user_id = $request->get('user_id');//支付类型
        $pay_type = $request->get('pay_type');//支付类型
        $trade_no = $request->get('trade_no', null);//银行卡交易号
        if (!$order_num || !$pay_type || !$user_id)
            Throw new AbstractException('参数异常！');
        $user_entity = $this->getRepository('AppBundle:User\Users')->find($user_id);
        if (!$user_entity) Throw new AbstractException('用户ID异常！');
        $order_entity = $this->getOrderRe()->findOneBy(['order_num' => $order_num, 'user_id' => $user_id]);
        if (!$order_entity) throw new AbstractException('订单编号不存在！');
        try {
            $aliPay = new AliPayController();
            $res = $aliPay->aliTradeQuery($order_num, $trade_no);
            $res = $res->alipay_trade_query_response;
            if (!$res)
                return $this->err('查询失败！');
            if ($res->code == 10000 && $res->trade_status == 'TRADE_SUCCESS') {
                if ($order_entity->getStatus() == self::PAYMENT_STATUS_WAIT) {
                    $order_entity->setStatus(self::PAYMENT_STATUS_SUCCESS);
                    $order_entity->setPaymentTime(date('Y-m-d H:i:s'));
                    $order_entity->setTradeNo($res->trade_no);
                    $order_entity->setBuyerLogonId($res->buyer_logon_id);
                    $this->editOrderItemStatus($order_num, self::PAYMENT_STATUS_SUCCESS);//修改对应详情表状态
                    $this->flush();
                    return $this->suc('ok');
                } elseif ($order_entity->getStatus() == self::PAYMENT_STATUS_SUCCESS) {
                    return $this->suc('ok');
                } else {
                    return $this->suc('ok');
                }
            } else {
                return $this->err('交易未支付！');
            }
        } catch (\Exception $e) {
            return $this->err('交易订单查询错误，请联系客服或相关人员！');
        }
    }

    /**
     * 银行卡支付异步通知
     * @Route("/bank/pay/order/notify",name="bank_order_callback")
     * @param Request $request
     */
    public function payCallbackNotify(Request $request)
    {
        $this->write_log("bankpayordernotify");
        $requestData = $request->request->all();
        $path = $this->get('kernel')->getRootDir() . '/../web/pay_logs/';//log地址
        if (!file_exists($path))
            mkdir($path);
        $name = date('Y-m-d') . '.txt';
        $path = $path . $name;
        file_put_contents($path, '【' . date('Y-m-d H:i:s') . '】 支付异步通知' . PHP_EOL, FILE_APPEND);
        $flag = $aliPay->payCallbackNotify($path, $requestData);
        if ($flag) {// 验签成功后
            //校验支付结果中app_id是否一致、收款商家UID是否一致,商家账号是否一致
            //订单金额是否一致、订单编号是否正确存在
            $check_flag = $aliPay->checkAppIDAndSellerID($requestData['app_id'], $requestData['seller_id']);
            if ($check_flag['flag']) {// 校验成功后判断是退款通知还是支付通知
                $order_entity = $this->em()->getRepository('AppBundle:Health\HealthyOrder')
                    ->find($requestData['out_trade_no']);
                if (!$order_entity) {//订单号不存在
                    $message = '订单编号不存在！';
                    $res = 'failure';
                } else {
                    $total_price = $order_entity->getTotalAmount();//订单总金额
                    if ($requestData['refund_fee']) {//判断是否是退款通知
                        $message = '此为退款通知，暂时无效！';
                        $res = 'failure';
                    } else {//表示是交易支付通知
                        if ($total_price != $requestData['total_amount']) {//判断总金额是否一致
                            $message = '订单总金额异常！';
                            $res = 'failure';
                        } else {
                            if ($order_entity->getHealthyOrderStatus() == 2) {//如果状态为已付款
                                $order_entity->setHealthyOrderStatus(2);
                                $order_entity->setHealthyPaymentTime(date('Y-m-d H:i:s'));
                                $order_entity->setHealthyPaymentType(1);
                                $order_entity->setHealthyTradeNo($requestData['trade_no']);
                                $order_entity->setHealthySellerId($requestData['seller_id']);
                                $order_entity->setHealthyBuyerId($requestData['buyer_id']);
                                $order_entity->setHealthyBuyerLogonId($requestData['buyer_logon_id']);
                                $order_entity->setUpdatedAt(date('Y-m-d H:i:s'));
                                $message = '订单已付款！';
                                $res = 'success';
                            } else {
                                if ($requestData['trade_status'] == 'TRADE_SUCCESS') {//交易支付成功
                                    $order_entity->setHealthyOrderStatus(2);
                                    $order_entity->setHealthyPaymentTime(date('Y-m-d H:i:s'));
                                    $order_entity->setHealthyPaymentType(1);
                                    $order_entity->setHealthyTradeNo($requestData['trade_no']);
                                    $order_entity->setHealthySellerId($requestData['seller_id']);
                                    $order_entity->setHealthyBuyerId($requestData['buyer_id']);
                                    $order_entity->setHealthyBuyerLogonId($requestData['buyer_logon_id']);
                                    $order_entity->setUpdatedAt(date('Y-m-d H:i:s'));
                                    $message = '订单状态修改成功！-- 2';
                                    $res = 'success';
                                } else {
                                    $message = '交易状态无法识别，无法退款！';
                                    $res = 'failure';
                                }
                            }
                        }
                    }
                }

            } else {
                $message = $check_flag['msg'];
                $res = 'failure';
            }
        } else {
            //验签失败则记录异常日志，并在response中返回failure.
            $message = '验签失败！';
            $res = 'failure';
        }
        $this->em()->getConnection()->beginTransaction();
        try {
            $this->flush();
            $this->em()->getConnection()->commit();
            file_put_contents($path, '【' . date('Y-m-d H:i:s') . '】 结果: ' . $message . PHP_EOL . PHP_EOL . PHP_EOL, FILE_APPEND);
            echo $res;
            die;
        } catch (\Exception $exception) {
            $this->em()->getConnection()->rollBack();
            file_put_contents($path, '持久化数据失败！' . PHP_EOL, FILE_APPEND);
            echo 'failure';
            die;
        }
    }

    /**
     * 取消退款
     * @Route("bank/pay/refund/ancel",name="bank_refund_cancel")
     * @Method("GET")
     */
    public function payRefundCancel(Request $request)
    {
        $orderNum = $request->get('order_num');
        $userId = $request->get('user_id');
        if (!$orderNum || !$userId)
            Throw new AbstractException('参数错误！');
        $orderEntity = $this->getOrderRe()->find($orderNum);
        if (!$orderEntity)
            Throw new AbstractException('订单不存在！');
        if ($orderEntity->getUserId() != $userId)
            Throw new AbstractException('无权操作该订单！');
        $orderEntity->setStatus(self::PAYMENT_STATUS_SUCCESS);
        $orderEntity->setRefundFee(null);
        $orderEntity->setRefundReason(null);
        $orderEntity->setRefundTime(null);
        $this->editOrderItemStatus($orderNum, self::PAYMENT_STATUS_SUCCESS);
        $this->flush($orderEntity);
        return $this->suc('操作成功！');
    }

    /**
     * 通过inputID获取订单总价格
     * @Route("bank/pay/amount/id",name="bank_order_amount_id")
     */
    public function getTotalMoneyByInputId(Request $request)
    {
        $inputId = $request->get('id');
        if (!$inputId)
            Throw new AbstractException('ID错误！');
        $res = $this->em()->getRepository('AppBundle:InputInfo')->getMoneyByInputId1($inputId)->getQuery()->getResult();
        if (empty($res))
            Throw new AbstractException('无数据！');
        $res = $this->em()->getRepository('AppBundle:SampleInfo')->getMoneyByInputId2($inputId)->getQuery()->getResult();
        if (empty($res))
            Throw new AbstractException('暂无金额！');
        $amount = 0;
        foreach ($res as $value) {
            if (!is_numeric($value['actual_payment']))
                Throw new AbstractException('数据错误！');
            if ($value['actual_payment'] <= 0)
                Throw new AbstractException('实际收款金额为0，无需申请开票！');
            if ($value['ticket_state'] == 1)
                Throw new AbstractException('样本已经线下开票成功，请勿重复开票！');
            if ($value['state'] != 2)
                Throw new AbstractException('部分样本未完成财务审核！');
            $amount += $value['actual_payment'];
        }
        return $this->suc('ok', ['amount' => $amount]);

    }

//    /*
//     * 得到付款凭证
//     */
//    public function getPaymentVoucher($order_num){
//        $order_num=$order_num;
//        $this->getPaymentVoucher();
//
//    }
//
//    /* 生成支付二维码
//     *
//     */
//    public function makequer(){
//        $aliPay = new UnionPayController();
//        $str = $aliPay->aliTradeAppPay($healthy_order_number, $subject,$body,$total_price,$expire);
//    }
//    /* 验证签名
//     *
//     */
//   public function getAssian(){
//       $this->getAssian();
//   }


    /**
     * 错误返回
     */
    private function errorReturn()
    {
        $this->successReturn(599, 'Logical Processing Error', 'fail');
    }

    /**
     * 成功返回
     * @param int $status 状态码
     * @param string $message 提示信息
     * @param string $tips 展示信息
     */
    private function successReturn($status = 200, $message = 'OK', $tips = 'success')
    {
        header("HTTP/1.1 {$status} {$message}");
        echo $tips;
        die;
    }


}
